package com.xing.binbackend.pattern.proxy21.beauty.staticp;

import com.xing.binbackend.pattern.proxy21.beauty.model.IUserService;
import com.xing.binbackend.pattern.proxy21.beauty.model.Request;
import com.xing.binbackend.pattern.proxy21.beauty.model.UserVo;

/**
 * 在不改变原始类（或叫被代理类）代码的情况下，通过引入代理类来给原始类附加功能。
 * <p>
 * 代码有2个问题
 * 1，计数器代码侵入到业务代码中，跟业务代码高度耦合。如果未来需要替换这个框架，那替换的成本会比较大。
 * 2. 收集接口请求的代码跟业务代码无关，本就不应该放到一个类中。
 * 业务类最好职责更加单一，只聚焦业务处理。
 */
public class UserServiceProxy implements IUserService {
    private final MetricsCollector metricsCollector;

    private final UserService userService;

    public UserServiceProxy(UserService userService) {
        this.metricsCollector = new MetricsCollector();
        this.userService = userService;
    }

    public UserVo login(String telephone, String password) {
        // 代理
        UserVo userVo = userService.login(telephone, password);
        long startTimestamp = System.currentTimeMillis();
        long endTimeStamp = System.currentTimeMillis();
        long responseTime = endTimeStamp - startTimestamp;
        Request request = new Request("login", responseTime, startTimestamp);
        metricsCollector.recordRequest(request);
        return userVo;
    }

    public UserVo register(String telephone, String password) {
        // 代理
        UserVo userVo = userService.register(telephone, password);
        long startTimestamp = System.currentTimeMillis();
        long endTimeStamp = System.currentTimeMillis();
        long responseTime = endTimeStamp - startTimestamp;
        Request request = new Request("register", responseTime, startTimestamp);
        metricsCollector.recordRequest(request);
        return userVo;
    }
}
